package sisi.enquires;

import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.event.InputEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Bandbox;
import org.zkoss.zul.Button;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Vbox;
import org.zkoss.zul.Window;

import sisi.Configuration;
import sisi.ConfigurationController;
import sisi.General;
import sisi.ports.Port;
import sisi.ports.PortController;
import sisi.status.StatusController;
import sisi.suppliers.Portssupplier;
import sisi.suppliers.PortssupplierController;
import sisi.suppliers.Supplier;
import sisi.suppliers.SupplierController;
import sisi.suppliers.Supplierproduct;
import sisi.suppliers.SupplierproductController;
import sisi.yacht.Anayacht;
import sisi.yacht.AnayachtController;


/**
 * ReqForAQuoteWindow.java - Controller class for <i>ReqForAQuoteWindow window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 10/3/2014
 * 
 */


@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class ReqForAQuoteWindow extends Window implements 
				org.zkoss.zk.ui.ext.AfterCompose {
//window
private Window finestraDettaglio, windowEditSupplierNote, windowEditAgentNote, windowRichiestaData;
private Listbox boxDetail, boxSuppliers, boxSuppliers2;
private Listbox boxBoatName, boxEnqNumber;

protected Map<String, Object> args;
// edit
//
private Textbox tbSearchBoatName, tbArt15, tbAgentID, tbAgentName, tbLocation;
private Bandbox bbBoatName, bbEnqNumber;
private Intbox idBoatName, idEnqNumber;
private Radiogroup rgChoices;
private Button btnLinkSupplier;
private Notesupp notesuppmod;
//
private Intbox ESNid, ESNidSupplier;
private Textbox ESNtbSupplier, ESNNote;
//
private Intbox EANid, EANidAgent;
private Textbox EANtbAgent, EANNote;
//
private Datebox dbData;

		public void onCreate$windowInvitationForAQuote(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();

		ListModelList listModelListYachts = new ListModelList();
		listModelListYachts.addAll(new AnayachtController().getAnayachtList(null));
		boxBoatName.setModel(listModelListYachts);
		boxBoatName.setItemRenderer(new BoatNameRenderer());

		tbSearchBoatName.addEventListener("onChanging", new EventListener() {

			public void onEvent(Event event) {
				final InputEvent evt = (InputEvent)event;
				String valore = evt.getValue();
				cercoYacht(valore);	
			}
		});

		bbBoatName.addEventListener("onChanging", new EventListener() {

			public void onEvent(Event event) {
				final InputEvent evt = (InputEvent)event;
				String valore = evt.getValue();
				cercoYacht(valore);	
			}
		});

		finestraDettaglio.setVisible(false);
		bbEnqNumber.setReadonly(true);
		idEnqNumber.setValue(null);
		
		Component tmp = finestraDettaglio.getFellow("boxDetail");
		boxDetail = (Listbox) tmp;
		btnLinkSupplier.setDisabled(true);
		
		boxDetail.addEventListener("onSelect", new EventListener() {
			public void onEvent(Event event){
				// aggiorno se selezionato: Select suppliers by product
				boxSuppliers.setSelectedIndex(-1);
				if (rgChoices.getSelectedIndex()==1){
					riempoBoxSuppliers();
				}				
			}		
		});
		
}
		
	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);
	}
	
	public void onClick$btnFiltroTipMov(Event event){
		cercoYacht(tbSearchBoatName.getValue());
	}
	
	private void cercoYacht(String nomeYacht){
		ListModelList listModelListYachts = new ListModelList();
		listModelListYachts.addAll(new AnayachtController().getAnayachtList(nomeYacht));
		boxBoatName.setModel(listModelListYachts);
		boxBoatName.invalidate();
		
		ListModelList listModelListEnqNumber = new ListModelList();
		//listModelListEnqNumber.addAll(new ReqshipfuelassController().getListaIdRichiesteAperteUnique(null));
		boxEnqNumber.setModel(listModelListEnqNumber);
		bbEnqNumber.setReadonly(true);
		
		idEnqNumber.setValue(null);
		bbEnqNumber.setValue("");
		rgChoices.setSelectedIndex(2);
		boxSuppliers.setVisible(false);
		
		finestraDettaglio.setVisible(false);
		
	}
	
	public void onSelect$boxBoatName(Event event){
		int iSelected = boxBoatName.getSelectedIndex();
		if (iSelected == -1){
			return;
		}
		Object oYacht = boxBoatName.getItemAtIndex(iSelected).getAttribute("rigaBoatName");
		Anayacht yacht = (Anayacht)oYacht;
		idBoatName.setValue(yacht.getId());
	
		// cerco enquires e faccio vedere id
		ListModelList listModelListEnqNumber = new ListModelList();
		listModelListEnqNumber.addAll(new ReqshipfuelassController().getListaIdRichiesteAperteUnique(yacht.getId()));
		boxEnqNumber.setModel(listModelListEnqNumber);
		boxEnqNumber.setItemRenderer(new EnqNumberRenderer());
		bbEnqNumber.setReadonly(false);

		idEnqNumber.setValue(null);
		finestraDettaglio.setVisible(false);
	}
	
	public void onSelect$boxEnqNumber(Event event){
		int iSelected = boxEnqNumber.getSelectedIndex();
		if (iSelected == -1){
			return;
		}
		Object oEnqNumber = boxEnqNumber.getItemAtIndex(iSelected).getAttribute("rigaEnqNumber");
		Object[] oRiga = (Object[])oEnqNumber;
		Integer id = (Integer)oRiga[0];
		idEnqNumber.setValue(id);

		finestraDettaglio.setVisible(true);
		viewDettaglio(id);
	}
	
	public void onChange$bbEnqNumber(Event event){
		if (bbEnqNumber.getValue()==null){
			return;
		}
		List lista = new ReqshipfuelassController().getListaIdRichiesteAperteUnique(idBoatName.getValue());
		boolean valido = false;
		for (Object object : lista) {
			Object[] oRiga = (Object[])object;
			Integer id = (Integer)oRiga[0];
			if ( Integer.valueOf( bbEnqNumber.getValue() ).compareTo(id)==0){
				idEnqNumber.setValue(id);
				valido = true;
				break;
			}
		}

		if (!valido){
			Messagebox.show("Enquire number not valid! - "+bbEnqNumber.getValue(), "Information", Messagebox.OK, Messagebox.INFORMATION);
			bbEnqNumber.setValue(null);
			finestraDettaglio.setVisible(false);
		} else {
			finestraDettaglio.setVisible(true);
			viewDettaglio(Integer.valueOf( bbEnqNumber.getValue() ));
		}
	}
		
	private void viewDettaglio(Integer idEnqNumber){
		ListModelList listModelListEnqNumber = new ListModelList();
		listModelListEnqNumber.addAll(new ReqshipfuelassController().getListaIdRichiesteAperteDettaglio(idEnqNumber));		
		boxDetail.setModel(listModelListEnqNumber);
		boxDetail.setItemRenderer(new EnqNumberDetailRenderer());
		riempoBoxSuppliers();
		
		// aggiorno dati agent id se c'è
		Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(idEnqNumber);
		if (reqshipfuelass.getAgentid()!=null && reqshipfuelass.getAgentid().compareTo(0)!=0){
			tbAgentID.setValue(""+reqshipfuelass.getAgentid());
			tbAgentName.setValue(reqshipfuelass.getAgent());
		}
		
		tbLocation.setValue(reqshipfuelass.getLocation());
		
		tbArt15.setValue( (reqshipfuelass.getArt15()==null||!reqshipfuelass.getArt15()?"NO":"SI") );
		
	}
		
		
	public void onCheck$rgChoices(Event event){
		riempoBoxSuppliers();
	} 
	
	private void riempoBoxSuppliers(){
		if (idEnqNumber.getValue()==null || idEnqNumber.getValue().compareTo(0)==0){
			boxSuppliers.setVisible(false);
			btnLinkSupplier.setDisabled(true);
			return;
		} else {
			boxSuppliers.setVisible(true);
			btnLinkSupplier.setDisabled(false);
		}
		
		ListModelList listModelListSuppliers = new ListModelList();
		if (rgChoices.getSelectedIndex()==0){
			boxSuppliers.setVisible(true);
			Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(idEnqNumber.getValue());
			//listModelListSuppliers.addAll( new PortssupplierController().getListXPortName(reqshipfuelass.getPorttoref()) );
			listModelListSuppliers.addAll( new PortssupplierController().getListXIdPort(reqshipfuelass.getIdportref()) );
			listModelListSuppliers.setMultiple(true);
			boxSuppliers.setItemRenderer(new PortSuppliersItemRenderer());
			boxSuppliers.setCheckmark(true);
			
		} else if (rgChoices.getSelectedIndex()==1){
			boxSuppliers.setVisible(true);
			Integer i = boxDetail.getSelectedIndex();
			if (i !=null && i.compareTo(-1)!=0  ){
				Object oDetail = boxDetail.getItemAtIndex(i).getAttribute(
						"rigaEnqDetailNumber");
				Object[] detail = (Object[])oDetail;
				Integer idProduct = (Integer)detail[3];
				if (idProduct != null){
					listModelListSuppliers.addAll( new SupplierproductController().getListxIdProduct(idProduct) );
					listModelListSuppliers.setMultiple(true);
				}
			}
			boxSuppliers.setItemRenderer(new SuppliersProductItemRenderer());
			boxSuppliers.setCheckmark(true);
			
		} else if (rgChoices.getSelectedIndex()==2) { 
			
			boxSuppliers.setVisible(false);
			
		}
		
		boxSuppliers.setModel(listModelListSuppliers);
		
		// prendo i suppliers diversi che ci sono nel dettaglio, e faccio elenco dei suppliers per stampare "Print ReqQuote"
		boxDetail.renderAll();
		List<Supplier> listSupplier = new ArrayList<Supplier>();
		for (int i = 0; i < boxDetail.getItemCount(); i++) {
			Object object = (Object)boxDetail.getItemAtIndex(i).getAttribute("rigaEnqDetailNumber");
			Object[] oRiga = (Object[])object;
			//Integer id = (Integer)oRiga[0];
			//Integer idSeq = (Integer)oRiga[1];
			//Integer idMaster = (Integer)oRiga[15];
			if (oRiga!=null){
				Integer idSupplier = (Integer)oRiga[13];
				if (idSupplier!=null){
					boolean trovato = false;
					for (Supplier supplier : listSupplier) {
						if (supplier.getSupplid().equals(idSupplier)){
							trovato = true;
						}
					}
					if (!trovato){
						Supplier supp = new SupplierController().getxId(idSupplier);
						listSupplier.add(supp);				
					}
				}
			}
		}
		ListModelList listModelListSuppliers2 = new ListModelList();
		listModelListSuppliers2.addAll( listSupplier );
		boxSuppliers2.setModel(listModelListSuppliers2);
		boxSuppliers2.setItemRenderer(new Suppliers2ItemRenderer());
		
	}
	
	
	public void onClick$btnLinkSupplier(Event event){
		
		Integer i = boxDetail.getSelectedIndex();
		if (i==null || i.compareTo(-1)==0){
			General.showNotify("No row selected. Please select a row to link.", null, 4000); 
			return;
		}
		
		Object oDetail = boxDetail.getItemAtIndex(i).getAttribute("rigaEnqDetailNumber");
		Object[] detail = (Object[])oDetail;
		Integer idRequest = (Integer)detail[0];
		Integer reqseq = (Integer)detail[1];
		String productName = (String)detail[2]; 
		Integer idProduct = (Integer)detail[3];
		Integer idMaster = (Integer)detail[15];
		
		Reqshipfuelass reqshipfuelassController = new ReqshipfuelassController().getxId(idRequest);
		Reqshipfuelassdetail reqshipfuelassdetail = new ReqshipfuelassdetailController().getxId(idMaster);

		if (idProduct != null){			
		}
		
		Set<Listitem> selectedSuppliers = boxSuppliers.getSelectedItems();
		
		for (Listitem listitem : selectedSuppliers) {

			Supplier supplier = new Supplier();
			
			if (rgChoices.getSelectedIndex()==0){
				// suppliers in port
				if (boxSuppliers.getSelectedIndex()>=0){
					
					Object oPortSupplier = listitem.getAttribute("rigaSupplier");		
					Portssupplier portsupplier = (Portssupplier)oPortSupplier;				
					supplier = new SupplierController().getxId(portsupplier.getSuppid());
				}
				
			} else if (rgChoices.getSelectedIndex()==1){
				// suppliers by product
				if (boxSuppliers.getSelectedIndex()>=0){
					Object oSupplierProduct = listitem.getAttribute("rigaSupplier");
					Supplierproduct supplierProduct = (Supplierproduct)oSupplierProduct;				
					supplier = new SupplierController().getxId(supplierProduct.getSupid());
				}
			}
	
			if (supplier.getSupplid()!=null){
				boolean trovato = false;
				List<Reqquote> listReqquote = new ReqquoteController().getList(idEnqNumber.getValue());
				for (Reqquote reqquote : listReqquote) {
					if (reqquote.getSuppid().equals(supplier.getSupplid()) && reqquote.getProdid().equals(idProduct) ){
						trovato = true;
						break;
					}
				}
				if (trovato){
					Messagebox.show("You tried to link supplier: " + supplier.getCompanyname().trim() + " to a record that is already linked to!", "Information", Messagebox.OK, Messagebox.INFORMATION);
				} else {
					// aggiungo riga
					Reqquote reqquote = new Reqquote();
					reqquote.setPortid(reqshipfuelassController.getIdportref());
					reqquote.setProdid(idProduct);
					reqquote.setProdname(productName);
					reqquote.setReqid(idRequest);
					reqquote.setReqseq(reqseq);			
					reqquote.setSuppid(supplier.getSupplid());
					reqquote.setSupname(supplier.getCompanyname());
					new ReqquoteController().add(reqquote);
					//
					reqshipfuelassdetail.setStat("IQ");
					reqshipfuelassdetail.setSupplierid(supplier.getSupplid());
					new ReqshipfuelassdetailController().update(reqshipfuelassdetail);
					
				}
			}
		}
		// refresh detail
		viewDettaglio(Integer.valueOf( bbEnqNumber.getValue() ));
		
	}
	
	
	public void onClick$btnSupplierNotes(Event event){
		int i = boxDetail.getSelectedIndex();
		if (i==-1){
			return;
		}
		Object oDetail = boxDetail.getItemAtIndex(i).getAttribute("rigaEnqDetailNumber");
		Object[] detail = (Object[])oDetail;
		Integer idRequest = (Integer)detail[0];
		Integer idSupplier = (Integer)detail[13];
		if (idSupplier!=null){
			Notesupp notesupp = new NotesuppController().getxIdReqEIdSupplier(idRequest, idSupplier);

			if (notesupp.getId()==null){
				notesupp.setId(idRequest);
				notesupp.setSuppid(idSupplier);
			}
			Sessions.getCurrent().setAttribute("NoteSupplier", notesupp);
			
			Window finestraSupplierNote = (Window) Executions.createComponents(
					"/editSupplierNote.zul", null, null);
			finestraSupplierNote.doModal();
			
			notesuppmod = (Notesupp) Sessions.getCurrent().getAttribute("NoteSupplierMod");
			if (notesuppmod!=null){
				if (notesuppmod.getIdmaster()==null){
					new NotesuppController().add(notesuppmod);
				} else {
					new NotesuppController().update(notesuppmod);
				}
			}
			Sessions.getCurrent().setAttribute("NoteSupplier", null);
			Sessions.getCurrent().setAttribute("NoteSupplierMod", null);
		}
	}
		
	public void onCreate$windowEditSupplierNote(Event event) {

		notesuppmod = (Notesupp) Sessions.getCurrent().getAttribute("NoteSupplier");
		
		Supplier supplier = new SupplierController().getxId(notesuppmod.getSuppid());
		
		ESNid.setValue(notesuppmod.getId());
		ESNidSupplier.setValue(supplier.getSupplid());
		ESNtbSupplier.setValue(supplier.getCompanyname());
		
		ESNNote.setValue(notesuppmod.getNotes());
	
	}	

	public void onClick$btnConferma2(Event event){
		notesuppmod.setNotes(ESNNote.getValue());
		Sessions.getCurrent().setAttribute("NoteSupplierMod", notesuppmod);
		windowEditSupplierNote.detach();
	}
	
	public void onClick$btnAnnulla2(Event event){
		windowEditSupplierNote.detach();
	}
	
	
	
	
	
	public void onClick$btnAgentNotes(Event event){
		
		
		if ( tbAgentID.getValue() == null || tbAgentID.getValue().isEmpty() || bbEnqNumber.getValue() == null || bbEnqNumber.getValue().isEmpty() ){
			General.showNotify("You can't edit Agent's note: there is no agent assigned to", null, 4000);
			return;
		}
		
		Integer idRequest = Integer.valueOf( bbEnqNumber.getValue() ); 

		Sessions.getCurrent().setAttribute("idRequest", idRequest);
			
		Window finestraAgentNote = (Window) Executions.createComponents(
				"/editAgentNote.zul", null, null);
		finestraAgentNote.doModal();
			
		Sessions.getCurrent().setAttribute("idRequest", null);
			
	}
	
	
	public void onCreate$windowEditAgentNote(Event event) {

		Integer idRequest = (Integer) Sessions.getCurrent().getAttribute("idRequest");
		Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(idRequest);
		
		EANid.setValue(idRequest);
		EANidAgent.setValue(reqshipfuelass.getAgentid());
		EANtbAgent.setValue(reqshipfuelass.getAgent());
		EANNote.setValue(reqshipfuelass.getNotea());
	
	}	

	public void onClick$btnConferma3(Event event){		
		Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(EANid.getValue());
		reqshipfuelass.setNotea(EANNote.getValue());
		new ReqshipfuelassController().update(reqshipfuelass);
		windowEditAgentNote.detach();
	}
	
	public void onClick$btnAnnulla3(Event event){
		windowEditAgentNote.detach();
	}
	
	public void onClick$btnAgentNomination(Event event){
		Configuration conf = new ConfigurationController().getxId(1);
		EANNote.setValue(conf.getAgentnomination());
	}
	
	public void onClick$btnAgentInformation(Event event){
		Configuration conf = new ConfigurationController().getxId(1);
		EANNote.setValue(conf.getAgentinformation());
	}

	
	public void onClick$btnPrintReqQuote(Event event) throws FileNotFoundException, SQLException, JRException {
		printReqQuote();
	}
	
	public void onClick$btnPrintAgentNomination(Event event) throws FileNotFoundException, SQLException, JRException {
		printAgentInformationNomination("AgentNomination", idEnqNumber.getValue(), tbAgentID, null);
	}
	
	public void onClick$btnPrintAgentInformation(Event event) throws FileNotFoundException, SQLException, JRException {
		printAgentInformationNomination("AgentInformation", idEnqNumber.getValue(), tbAgentID, null);
	}
	
	public void onClick$btnBerthAssignement(Event event) throws FileNotFoundException, SQLException, JRException {
		printBerthAssignment(idEnqNumber.getValue());
	}
	
	private void printReqQuote() throws SQLException, JRException, FileNotFoundException {
		int nIndex = boxSuppliers2.getSelectedIndex();

		if ( nIndex == -1) { // nessuna riga selezionata

			Messagebox.show("Select a Supplier", "Information", Messagebox.OK, Messagebox.INFORMATION);
			return;

		} 

		Sessions.getCurrent().setAttribute("richiestaData", null);
		
		Window finestraReqDate = (Window) Executions.createComponents(
				"/richiestaData.zul", null, null);
		finestraReqDate.doModal();

		
		Date data = (Date) Sessions.getCurrent().getAttribute("richiestaData");
		if (data==null){
			return;
		}
		
		
		
		Sessions.getCurrent().setAttribute("richiestaData", null);
		
		Object oSupplier = boxSuppliers2.getSelectedItem().getAttribute("rigaSupplier");
		Supplier supplier = (Supplier) oSupplier;

		
		String _utente = (String)Sessions.getCurrent().getAttribute("_utente"), _password = (String)Sessions.getCurrent().getAttribute("_password");
		
		String url = "jdbc:postgresql://localhost/pico";
		Properties props = new Properties();
		props.setProperty("user", _utente );
		props.setProperty("password", _password );
		Connection connection = DriverManager.getConnection(url, props); 
		

		// setup parameters for use with the report
		HashMap<String, Object> params = new HashMap<String,Object>();
		//params.put( "ordine", fa.getRef() );
		params.put( "PATH_IMG", new General().percorsoImg() + "/" );
		params.put( "PAR_REQUEST_ID", idEnqNumber.getValue() );
		params.put( "PAR_SUPPLIER_ID", supplier.getSupplid() );
		params.put( "PAR_DATA", data);

		// Fill the report data from the sql connection and parameters
		JasperPrint printedReport;
		String fileJasper = new General().percorsoFincati()+"/RequestQuote.jasper";
		//System.out.println(fileJasper);
		
		printedReport = JasperFillManager.fillReport(fileJasper, params, connection);

		String outputFilename = new General().percorsoEsporta()+"/RequestQuote.pdf";
		//System.out.println(outputFilename);
		
		JasperExportManager.exportReportToPdfFile( printedReport, outputFilename );

		File file = new File(outputFilename);
		Filedownload.save(file, "PDF");
		
		
	}
	
	public void printAgentInformationNomination(String nomeFile, Integer idEnqNumber, Textbox tbAgentID, String location) throws SQLException, JRException, FileNotFoundException {

		if ( tbAgentID.getValue() == null || tbAgentID.getValue().isEmpty() || idEnqNumber == null){
			General.showNotify("You can't print agent report: there is no agent assigned to", null, 4000);
			return;
		}

	 
		String _utente = (String)Sessions.getCurrent().getAttribute("_utente"), _password = (String)Sessions.getCurrent().getAttribute("_password");
		
		String url = "jdbc:postgresql://localhost/pico";
		Properties props = new Properties();
		props.setProperty("user", _utente );
		props.setProperty("password", _password );
		Connection connection = DriverManager.getConnection(url, props);
		

		// setup parameters for use with the report
		HashMap<String, Object> params = new HashMap<String,Object>();
		//params.put( "ordine", fa.getRef() );
		params.put( "PATH_IMG", new General().percorsoImg() + "/" );
		params.put( "PAR_REQUEST_ID", idEnqNumber );
		//params.put( "PAR_SUPPLIER_ID", supplier.getSupplid() );
		params.put( "PAR_DATA", new Date());
		params.put( "PAR_LOCATION", General.trimNull(location) );

		// Fill the report data from the sql connection and parameters
		JasperPrint printedReport;
		String fileJasper = new General().percorsoFincati()+"/"+nomeFile+".jasper";
		//System.out.println(fileJasper);
		
		printedReport = JasperFillManager.fillReport(fileJasper, params, connection);

		String outputFilename = new General().percorsoEsporta()+"/"+nomeFile+".pdf";
		//System.out.println(outputFilename);
		
		JasperExportManager.exportReportToPdfFile( printedReport, outputFilename );

		File file = new File(outputFilename);
		Filedownload.save(file, "PDF");
	}
	
	
	public void printBerthAssignment(Integer idEnqNumber) throws SQLException, JRException, FileNotFoundException {

		/*
		int nIndex = boxSuppliers2.getSelectedIndex();

		if ( nIndex == -1) { // nessuna riga selezionata

			Messagebox.show("Select a Supplier", "Information", Messagebox.OK, Messagebox.INFORMATION);
			return;

		} 
		*/	
	 
		String _utente = (String)Sessions.getCurrent().getAttribute("_utente"), _password = (String)Sessions.getCurrent().getAttribute("_password");
		
		String url = "jdbc:postgresql://localhost/pico";
		Properties props = new Properties();
		props.setProperty("user", _utente );
		props.setProperty("password", _password );
		Connection connection = DriverManager.getConnection(url, props);
		

		// setup parameters for use with the report
		HashMap<String, Object> params = new HashMap<String,Object>();
		//params.put( "ordine", fa.getRef() );
		params.put( "PATH_IMG", new General().percorsoImg() + "/" );
		params.put( "PAR_REQUEST_ID", idEnqNumber );
		//params.put( "PAR_SUPPLIER_ID", supplier.getSupplid() );
		params.put( "PAR_DATA", new Date());

		// Fill the report data from the sql connection and parameters
		JasperPrint printedReport;
		String fileJasper = new General().percorsoFincati()+"/BerthAssignment.jasper";
		//System.out.println(fileJasper);
		
		printedReport = JasperFillManager.fillReport(fileJasper, params, connection);

		String outputFilename = new General().percorsoEsporta()+"/BerthAssignment.pdf";
		//System.out.println(outputFilename);
		
		JasperExportManager.exportReportToPdfFile( printedReport, outputFilename );

		File file = new File(outputFilename);
		Filedownload.save(file, "PDF");
	}
	
	public void onChange$tbLocation(Event event){
		Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(idEnqNumber.getValue());
		reqshipfuelass.setLocation(tbLocation.getValue());
		new ReqshipfuelassController().update(reqshipfuelass);
	}
	
	
	public void onCreate$windowRichiestaData(Event event) {

		dbData.setValue(new Date());

	}	
	
	public void onClick$btnConfermaData(Event event){
		
		Sessions.getCurrent().setAttribute("richiestaData", dbData.getValue());
		windowRichiestaData.detach();
	}
	

	public void onClick$btnAnnullaData(Event event){
		windowRichiestaData.detach();		
	}

	
	public class RendererDetail implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			
			Reqshipfuelassdetail detail = ((Reqshipfuelassdetail) data);
			
			new Listcell(""+detail.getId()).setParent(li);
			new Listcell(""+detail.getSeq()).setParent(li);
			new Listcell(""+detail.getProductid()).setParent(li);
			
			Listcell cellProductname = new Listcell(detail.getProductname());
			cellProductname.setStyle("white-space:nowrap;overflow:hidden");
			cellProductname.setParent(li);
			new Listcell(""+detail.getQuantity()).setParent(li);
			new Listcell(detail.getUm()).setParent(li);
			new Listcell(detail.getStat()).setParent(li);
			Listcell cellNote = new Listcell(""+detail.getNote());
			cellNote.setStyle("white-space:nowrap;overflow:hidden");
			cellNote.setParent(li);
			li.setAttribute("rigaDetail", data);
			
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClickedDetail");
		}
	}

	
	private class BoatNameRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			Anayacht yacht = (Anayacht)data;
			new Listcell(yacht.getName()).setParent(item);
			new Listcell(""+yacht.getId()).setParent(item);
			new Listcell(yacht.getCorporation()).setParent(item);
			item.setAttribute("rigaBoatName", data);
		}
	}
	

	private class EnqNumberRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Object[] oRiga = (Object[])data;
			Integer id = (Integer)oRiga[0];

			Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(id);

			Port port = new PortController().getPortxId(reqshipfuelass.getIdportref());
			
			new Listcell(""+id).setParent(item);
			new Listcell(""+General.formatoFecha(reqshipfuelass.getDeliverydt())).setParent(item);
			new Listcell(""+reqshipfuelass.getPorttoref()).setParent(item);
			new Listcell(""+port.getCountry()).setParent(item);
			item.setAttribute("rigaEnqNumber", data);
		}
	}

	
	private class SuppliersProductItemRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Supplierproduct supplierProduct = (Supplierproduct)data;

			
			new Listcell(""+supplierProduct.getSupname()).setParent(item);
			new Listcell(""+supplierProduct.getSupid()).setParent(item);
			item.setAttribute("rigaSupplier", data);
		}
	}

	private class PortSuppliersItemRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Portssupplier portsupplier = (Portssupplier)data;
			
			Supplier supplier = new SupplierController().getxId(portsupplier.getSuppid());
			
			
			new Listcell(""+supplier.getCompanyname()).setParent(item);
			new Listcell(""+supplier.getSupplid()).setParent(item);
			item.setAttribute("rigaSupplier", data);
		}
	}
	
	
	private class Suppliers2ItemRenderer implements ListitemRenderer {

		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Supplier supplier = (Supplier)data;
			
			new Listcell(""+supplier.getCompanyname()).setParent(item);
			item.setAttribute("rigaSupplier", data);
		}
	}
	
	private class EnqNumberDetailRenderer implements ListitemRenderer {
	
		@Override
		public void render(Listitem item, Object data, int index)
				throws Exception {
			
			Object[] oRiga = (Object[])data;
			Integer id = (Integer)oRiga[0];
			Integer idSeq = (Integer)oRiga[1];
			Integer idMaster = (Integer)oRiga[15];
			Integer idSupplier = (Integer)oRiga[13];
			
			Reqshipfuelassdetail reqshipfuelassdetail = new ReqshipfuelassdetailController().getxId(idMaster);

			//Reqshipfuelass reqshipfuelass = new ReqshipfuelassController().getxId(id);
			//Port port = new PortController().getPortxId(reqshipfuelass.getIdportref());
			
			Textbox tbIdEnq = new Textbox(""+id);
			tbIdEnq.setWidth("80px");
			tbIdEnq.setReadonly(true);
			
			
			
			Textbox tbRowNumber = new Textbox("" + General.paddingString(""+idSeq, 2, '0', true) + " of "+ General.paddingString(""+boxDetail.getModel().getSize(), 2, '0', true ) );
			tbRowNumber.setWidth("60px");
			tbRowNumber.setReadonly(true);
			
			Textbox tbProductName = new Textbox(reqshipfuelassdetail.getProductname());
			tbProductName.setWidth("250px");
			tbProductName.setRows(2);
			tbProductName.setReadonly(true);
			
			Textbox tbProductId = new Textbox(""+reqshipfuelassdetail.getProductid());
			tbProductId.setWidth("60px");
			tbProductId.setReadonly(true);
			
			Textbox tbQuantity = new Textbox( General.decimalFormat("#,##0.000", reqshipfuelassdetail.getQuantity()) );
			tbQuantity.setWidth("80px");
			tbQuantity.setReadonly(true);
			
			Textbox tbUM = new Textbox(""+reqshipfuelassdetail.getUm());
			tbUM.setWidth("60px");
			tbUM.setReadonly(true);


			Textbox tbCodStatus = new Textbox(""+reqshipfuelassdetail.getStat());
			tbCodStatus.setWidth("40px");
			tbCodStatus.setReadonly(true);

			Textbox tbDesStatus = new Textbox(""+new StatusController().getXCodice(reqshipfuelassdetail.getStat(), false).getDescription() );
			tbDesStatus.setWidth("200px");
			tbDesStatus.setReadonly(true);

			
			Label lblNote = new Label("Note");
			lblNote.setStyle("color:blue");
			
			String note = reqshipfuelassdetail.getNote();
			note = (note==null?"":note);
			Textbox tbRigaNota = new Textbox(""+note);
			tbRigaNota.setWidth("200px");
			tbRigaNota.setReadonly(true);
			tbRigaNota.setRows(4);
			tbRigaNota.setCols(25);

			Label lblSupplier = new Label("Supplier: ");
			lblSupplier.setStyle("color:blue");
			String supplierName = "";
			if (idSupplier!=null){
				Supplier supplier = new SupplierController().getxId(idSupplier);
				
				if (supplier!=null){
					supplierName = supplier.getCompanyname();
				}
			}
			Textbox tbSupplier = new Textbox(supplierName);
			tbSupplier.setWidth("200px");
			tbSupplier.setReadonly(true);

			Label lblSequenceNote = new Label("Sequence Note");
			lblSequenceNote.setStyle("color:blue");
			
			String sequenceNote = "";
			Boolean tbReadOnly = true;
			
			if (idSupplier!=null){
				tbReadOnly = false;
				Notesuppseqt notesupp = new NotesuppseqtController().getxIdReqEIdSupplier(id, idSupplier, idSeq );
				if (notesupp!=null){
					sequenceNote = notesupp.getNote();
				}
			}

			Textbox tbSequenceNote = new Textbox(sequenceNote);
			tbSequenceNote.setWidth("200px");
			tbSequenceNote.setReadonly(tbReadOnly);
			tbSequenceNote.setRows(4);
			tbSequenceNote.setCols(25);
			
			tbSequenceNote.addEventListener("onChange", new EventListener() {
				public void onEvent(Event event) {
					final InputEvent evt = (InputEvent) event;
					String valore = evt.getValue();
					
					Component componente = event.getTarget();
					Integer iIndex = ((Listitem)componente.getParent().getParent().getParent().getParent()).getIndex();
					Object oRigaDetail = boxDetail.getItemAtIndex(iIndex).getAttribute("rigaEnqDetailNumber");
	
					
					Object[] oRiga = (Object[])oRigaDetail;
					Integer id = (Integer)oRiga[0];
					Integer idSeq = (Integer)oRiga[1];
					Integer idSupplier = (Integer)oRiga[13];
					
					Notesuppseqt notesuppseqt = new NotesuppseqtController().getxIdReqEIdSupplier(id, idSupplier, idSeq);
					if (notesuppseqt.getId()==null){ // insert
						notesuppseqt.setIdrequest(id);
						notesuppseqt.setIdsupplier(idSupplier);
						notesuppseqt.setSeq(idSeq);
						notesuppseqt.setNote(valore);
						new NotesuppseqtController().add(notesuppseqt);
					} else { // update
						notesuppseqt.setNote(valore);
						new NotesuppseqtController().update(notesuppseqt);
					}
				}
			});

			
			Textbox tbIdSupplier = new Textbox(""+(idSupplier==null?"":idSupplier));
			tbIdSupplier.setWidth("40px");
			tbIdSupplier.setReadonly(true);

			
			Vbox vbox1 = new Vbox();
			Hbox hbox1 = new Hbox();
			Hbox hbox2 = new Hbox();
			
			hbox1.appendChild(tbIdEnq);
			hbox1.appendChild(tbRowNumber);
			hbox1.appendChild(tbProductName);
			hbox1.appendChild(tbProductId);
			hbox1.appendChild(tbQuantity);
			hbox1.appendChild(tbUM);
			hbox1.appendChild(tbCodStatus);
			hbox1.appendChild(tbDesStatus);
			
			hbox2.appendChild(lblNote);
			hbox2.appendChild(tbRigaNota);
			hbox2.appendChild(lblSupplier);
			hbox2.appendChild(tbIdSupplier);
			hbox2.appendChild(tbSupplier);
			hbox2.appendChild(lblSequenceNote);
			hbox2.appendChild(tbSequenceNote);
			
			vbox1.appendChild(hbox1);
			vbox1.appendChild(hbox2);
			
			Listcell listcell = new Listcell();
			
			listcell.appendChild(vbox1);
			
			listcell.setParent(item);
			
			/*
				<listitem>
					<listcell>
						<vbox id="vbox1">
							<hbox id="hbox1">
								<textbox id="tbIdEnq" value="5217" width="80px" readonly="true" />
								<textbox id="tbRowNumber" value="02 of 01" width="60px" readonly="true" />
								<textbox id="tbProductName" value="AUTOMOTIVE GAS OIL - AGO - SULPHUR CONT. 0,005% MAX" rows="2" width="250px" readonly="true" />
								<textbox id="tbProductId" value="324" width="60px" readonly="true"  />
								<textbox id="tbQuantity" value="35.000,000" cols="12" style="text-align:right;"  readonly="true" width="80px" />
								<textbox id="tbUM" value="EACH" width="60px" readonly="true" />
								<textbox id="tbCodStatus" value="IQ" width="40px" readonly="true"  />
								<textbox id="tbDesStatus" value="INVITATION FOR A QUOTE" width="200px" readonly="true" />
							</hbox>
							<hbox id="hbox2">								
								<textbox id="tbRigaNota" value="RIGA DI NOTA RIGA DI NOTA RIGA DI NOTA" cols="25" rows="4" width="200px" readonly="true"  />
								<label value="Supplier:" />
								<textbox id="tbSupplier" value="EXXONMOBIL MARINE FUELS" width="200px" readonly="true" />
								<textbox id="tbIdSupplier" readonly="true" />
								<label value="Sequence Note" />
							</hbox>
						</vbox>
					</listcell>
				</listitem>
			*/
			
			item.setAttribute("rigaEnqDetailNumber", data);
		}
	}
	
}
